#include "BaseInc.h"
#include "WindowSDL.h"

void WindowSDL::MakeWindow()
{
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
	rect = { 200,200,600,480 };
	window = SDL_CreateWindow("WindowSDL", rect.x, rect.y, rect.w, rect.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
	context = SDL_GL_CreateContext(window);
	render = SDL_CreateRenderer(window, 0, SDL_VIDEO_RENDER_OGL);
	SDL_RenderSetViewport(render, &rect);
	SDL_GL_MakeCurrent(window, context);

}

INT WindowSDL::ShowModal()
{
	while (true)
	{
		SDL_WaitEvent(&evt);
		DoEvent(&evt);
		switch (evt.type) {
		case SDL_QUIT:
			break;
			break;
		}
		glViewport(0, 0, rect.w, rect.h);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		//gluPerspective(60, rect.w / (float)rect.h, 0.1, 1000);
		gluOrtho2D(0, rect.w, rect.h, 0);
		//gluOrtho2D(0, rect.w, 0,rect.h);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glClear(GL_COLOR_BUFFER_BIT);
		glClear(GL_DEPTH_BUFFER_BIT);
		glClearColor(0.3, 0.3, 0.3, 1.);
		//gluLookAt(0, 0, 100, 0, 0, 0, 0, 1, 0);
		OnDraw();
		SDL_GL_SwapWindow(window);
	}
	return IDOK;
}

void WindowSDL::DoEvent(SDL_Event* evt)
{
	switch (evt->type)
	{
	case SDL_KEYDOWN:
		break;
	case  SDL_KEYUP:
		break;
	case SDL_SYSWMEVENT:
		break;
	case SDL_WINDOWEVENT:
		break;
	case SDL_MOUSEBUTTONDOWN:
		break;
	case SDL_MOUSEWHEEL:
		break;
	case SDL_QUIT:
		break;
	default:
		break;
	}


}

void WindowSDL::OnClosed()
{
	SDL_DestroyRenderer(render);
	SDL_DestroyWindow(window);
}

void WindowSDL::OnDraw()
{
	glBegin(GL_QUADS);
	glColor3f(1.0, 1.0, 1.0); glVertex3f(0, 0, 0);
	glColor3f(1.0, 1.0, 0.0); glVertex3f(100, 0, 0);
	glColor3f(0.0, 1.0, 1.0); glVertex3f(100, 100, 0);
	glColor3f(0.0, 1.0, 1.0); glVertex3f(0, 100, 0);
	glEnd();
}

void WindowSDL::OnSizeChange()
{

}

std::pair<tstring, Control*> WindowSDL::HitTestContrl(vec2 pos)
{
	for (int i = 0; i < childs.size(); i++)
	{
		if (childs[i].second->HitTest(pos))
		{
			return childs[i];
		}
	}
	return std::make_pair<tstring,Control*>(_T(""),nullptr);
}

